/**
 * <pre>
 * 紫光软件系统有限公司广电事业部
 * Copyright (C): 2011
 * 
 * 文件名称：
 * com.unis.iptv.service.impl.LiveServiceImpl.java
 * 
 * 文件描述: 
 * TODO
 * 
 * Notes:
 * 修改历史(作者/日期/改动描述):
 * 杨飞宇/2013-1-3/初始化版本。
 * </pre>
 */
package com.unis.iptv.service.impl;

import static com.unis.iptv.client.ClientCustomContext.executeRequest;
import static com.unis.iptv.client.ClientCustomContext.getCustomContext;
import static com.unis.iptv.common.utils.GlobalUtil.baseUrl;

import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.unis.iptv.dao.ChannelDao;
import com.unis.iptv.dao.DailyScheduleDao;
import com.unis.iptv.domain.Channel;
import com.unis.iptv.domain.DailySchedule;
import com.unis.iptv.service.LiveService;

/**
 * @date 2013-1-3
 * @author 杨飞宇
 */
@Service
public class LiveServiceImpl implements LiveService {
	private static Log log = LogFactory.getLog("iptvCourse");
	private static Log errLog = LogFactory.getLog("iptvErrCourse");
	@Autowired
	private ChannelDao channelDao;
	
	@Autowired
	private DailyScheduleDao dailyScheduleDao;
	
	@Override
	public void execute() {
		log.info("直播频道提取开始！");
		
		try {
			log.info("回看");
			executeRequest(baseUrl
					+ "/iptvepg/frame1008/portal_key.jsp?Action=2");
			String html = getCustomContext(baseUrl
					+ "/iptvepg/frame1008/tvod_portal.jsp");
			
			String regex = "eval\\(\"\\(\\[\\{[^]]*\\]},\\{'pageCount':'\\d+','pageNum':'\\d+','data':\\[(.*)\\]\\}\\]\\)\"\\)";
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(html);
			if (m.find()) {
				html = m.group(1);
			}
			regex = "\\{'channelId':'(\\S+)', 'channelName':'(\\S+)', 'columnId':'(\\S+)', 'mixNo':'(\\S+)', 'userTvodEnable':''\\}";
			p = Pattern.compile(regex);
			m = p.matcher(html);
			while (m.find()) {
				Channel channel = new Channel();
				Integer channelId = channelDao.getChannelId();
				channel.setChannelId(channelId);
				String channelid = m.group(1);
				String columnid = m.group(3);
				String channelName = m.group(2);
				channel.setChannelName(channelName);
				String channelNumber = m.group(4);
				channel.setChannelNumber(channelNumber);
				log.info("回看频道:" + channelName);
				channelDao.saveChannel(channel);
				getDailySchedule(channelId, columnid, channelid, channelNumber,
						channelName);
			}
		} catch (Exception e) {
			e.printStackTrace();
			errLog.error("直播提取失败" + e.getMessage());
		}
	}
	
	private void getDailySchedule(Integer channelId, String columnid,
			String channelid, String channelNumber, String channelName)
			throws Exception {
		String scheduleUrl = baseUrl
				+ "/iptvepg/frame1008/tvod_list.jsp?columnid=" + columnid
				+ "&channelid=" + channelid + "&mixNo=" + channelNumber
				+ "&title=" + URLEncoder.encode(channelName, "GBK");
		String html = getCustomContext(scheduleUrl);
		// 先取pageCount {'pageCount':'4','
		String regex = "'pageCount':'(\\d+)'";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(html);
		int pageCount = 0;
		if (m.find()) {
			pageCount = Integer.parseInt(m.group(1));
		}
		scheduleUrl = getAllDailyScheduleUrl(channelid, columnid, pageCount);
		html = getCustomContext(scheduleUrl);
		
		regex = "\\{'programName':'(\\S+)', 'isPlayable':'\\S+', 'contentId':'\\S+', 'channelId':'\\S+', 'startTime':'(\\S+)', 'endTime':'(\\S+)'\\}";
		p = Pattern.compile(regex);
		m = p.matcher(html);
		while (m.find()) {
			String programName = m.group(1);
			String startTime = m.group(2);
			String endTime = m.group(3);
			DailySchedule dailySchedule = new DailySchedule();
			dailySchedule.setChannelId(channelId);
			dailySchedule.setStartTime(startTime.replace(":", "") + "00");
			dailySchedule.setProgramName(programName);
			dailySchedule.setEndTime(endTime.replace(":", "") + "00");
			log.info("                 回看节目:" + programName);
			dailyScheduleDao.saveDaillySchedule(dailySchedule);
		}
		
	}
	
	/**
	 * @author 杨飞宇 @2013-1-4
	 * @param destpage
	 *            第几页 此处固定给1 写死
	 * @param numperpage
	 *            准备取多少 机顶盒固定是10 我们点回看频道后按照共有多少面来算（在上一个页面的pageCount里取
	 *            乘以10,但必须是destpage=1里 否则取不到数据）
	 * @param channelid
	 *            回看频道属性
	 * @param columnid
	 *            回看频道属性
	 * @param datelistid
	 *            天的索引 0为明天 1为当天 现在固定写死只取1天
	 * @param pageCount
	 *            回看频道中取到的总页数 例pageCount {'pageCount':'4','
	 * @return 拼接成的URL
	 */
	private static String getAllDailyScheduleUrl(String channelid,
			String columnid, int pageCount) {
		String url = baseUrl
				+ "/iptvepg/frame1008/get_tvod_data.jsp?destpage=1&numperpage="
				+ 10 * pageCount + "&channelid=" + channelid + "&columnid="
				+ columnid + "&datelistid=1";
		return url;
		
	}
}
